<template>
  <div v-loading="pageLoading" :class="{'mobile-create': showMobilePage}" class="reimbursement-create-container">
    <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
    <div :class="{'pb55':device!=='mobile'}" class="page-container">
      <baseInfo ref="baseInfoRef" v-model="baseInfo" :total-amount="totalReimbursementAmount" @typeChange="typeChange" />
      <AccountTable ref="accountTableRef" :is-create="!id" />
      <CommonProject v-if="baseInfo.type === 0" ref="commonProjectRef" v-model="totalReimbursementAmount" />
      <TravelProject v-else ref="travelProjectRef" v-model="totalReimbursementAmount" />
      <AllocationTable
        v-if="baseInfo.isAllocation === 1"
        ref="allocationTableRef"
        v-model="totalAllocationAmount"
        :dept-tree-list="deptTreeList" />
      <audit-process
        ref="auditProcess"
        :loading="loading"
        v-model="auditInfo"
        :old-audit-info="oldAuditInfo"
        :default-aduitor-list="[baseInfo.proposerObj]"

        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="submit(SUBMIT_TYPE.SUBMIT,$event)"
        @getProcess="getProcess" />
      <AssociatedApproval ref="associatedApprovalRef" :exclude-id="id" :module-id="FIXED_PROCESS_TYPE.REIMBURSEMENT" style="margin-top: 24px" />
      <fixed-pagination>
        <div class="center">
          <el-button size="small" type="primary" class="mobile-btn-flex" @click="openDrawer()">发起审批</el-button>
          <el-button v-if="(!remodifyId && !reapplyId) || createNew" size="small" type="info" class="back-btn empty-btn-style" @click="submit(SUBMIT_TYPE.DRAFT)">保存草稿</el-button>
          <el-button class="cancel-btn-style" size="small" @click="toBack">返回</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
// components
import BaseInfo from './module/baseInfo';
import AccountTable from '../module/accountTable';
import CommonProject from '../module/commonProject';
import TravelProject from '../module/travelProject';
import AllocationTable from '../module/allocationTable';
import AssociatedApproval from '../module/associatedApproval';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
// tool
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import { createAuditStructure } from '@/utils/aduitor';
import { SUBMITTYPE as SUBMIT_TYPE } from '@/utils/const/cost';
import { isContained } from '@/utils/tools';
import { FIXED_PROCESS_TYPE } from '@/utils/const/process';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';
// api
import {
  formSubmitReimbursement,
  storeReimbursement,
  editReimbursement,
  getReimbursementDetail
} from '@/api/reimbursement';
import { getDepartmentAll } from '@/api/config';
import { processManagementDetail } from '@/api/legal';
export default {
  components: {
    BaseInfo,
    AccountTable,
    CommonProject,
    TravelProject,
    AllocationTable,
    AuditProcess,
    AssociatedApproval,
    explanation
  },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      id: '',
      SUBMIT_TYPE,
      FIXED_PROCESS_TYPE,
      baseInfo: {
        proposerObj: {},
        avatar: '',
        proposerId: null, // 申请人
        proposer: null, // 申请人名字
        departmentId: null, // 申请部门
        company: null, // 所属公司
        type: 0, // 报销类型
        isAllocation: '', // 分摊费用
        isWriteOff: '', // 冲抵借款
        arrearsAmount: '', // 借款欠额
        writeOffAmount: '', // 冲抵借款欠额
        paymentAmount: '', // 实付金额
        attachment: [] // 附件
      },
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      }, // 流程信息
      processDetail: null,
      isEdit: false,
      remodifyId: null, // 修改，审批流程不能修改
      reapplyId: null, // 重新申请
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      loading: false,
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      pageLoading: false,
      deptTreeList: [],
      totalReimbursementAmount: null, // 总报销金额
      totalAllocationAmount: null, // 总分摊金额
      createNew: 0
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'userInfo': state => state.user.userInfo
    })
  },
  watch: {
  },
  created() {
    const id = this.$route.params.id;
    this.createNew = Number(this.$route.query.createNew) || 0;
    const remodifyId = this.$route.query.remodifyId; // 修改
    const reapplyId = this.$route.query.reapplyId; // 重新申请
    this.remodifyId = remodifyId;
    this.reapplyId = reapplyId;
    this.queryDeptTreeList();
    if (id) {
      this.id = id;
      this.isEdit = true;
      this.getData();
      this.reapplyId && this.getExplanation();
    } else {
      this.isEdit = false;
      this.getExplanation();
    }
  },
  methods: {
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        if (res.code === 200) {
          this.deptTreeList = res.data;
        }
      });
    },
    getData(id = this.id) {
      this.pageLoading = true;
      getReimbursementDetail(id).then(res => {
        if (res.code === 200) {
          this.baseInfo = res.data;
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          if (this.baseInfo.proposerId) {
            this.baseInfo.proposerObj = {
              id: this.baseInfo.proposerId,
              userName: this.baseInfo.proposer,
              avatar: this.baseInfo.avatar
            };
          }
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          this.$nextTick(() => {
            this.setFormData(res.data);
            this.pageLoading = false;
          });
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      }).catch(_ => {
        this.pageLoading = false;
      });
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    openDrawer() { // 2.9.7 流程弹窗
      const promise = [];
      promise.push(this.$refs['baseInfoRef'].validateForm());
      promise.push(this.$refs['accountTableRef'].validateForm());
      if (this.baseInfo.isAllocation === 1) {
        promise.push(this.$refs['allocationTableRef'].validateForm());
      }
      if (this.baseInfo.type === 0) {
        promise.push(this.$refs['commonProjectRef'].validateForm());
      } else {
        promise.push(this.$refs['travelProjectRef'].validateForm());
      }
      Promise.all(promise).then(() => { // 表单校验通过，则仅提交供应商表单部分，不提交流程信息，用来获取最新流程
        if (this.baseInfo.isWriteOff) {
          if (+this.totalReimbursementAmount < +this.baseInfo.writeOffAmount) {
            this.$message.warning('冲抵借款欠额不可大于总报销金额');
            return;
          } else if (+this.baseInfo.arrearsAmount < +this.baseInfo.writeOffAmount) {
            this.$message.warning('冲抵借款欠额不可大于借款欠额');
            return;
          }
        }
        this.getProcessDetail();
        // 重新申请或者新建
      }).catch((e) => {
        console.log(e);
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    // 报销类型清空总额
    typeChange() {
      this.totalReimbursementAmount = null;
    },
    // 获取审批说明
    getExplanation() {
      processManagementDetail({ id: 3527, type: 17 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取表单数据
    getFormData() {
      const params = _.cloneDeep(this.baseInfo);
      params.totalReimbursementAmount = this.totalReimbursementAmount;
      params.totalAllocationAmount = this.totalAllocationAmount;
      params.accountInfo = this.$refs['accountTableRef'].getTableData();
      if (this.baseInfo.isAllocation === 1) {
        params.allocationList = this.$refs['allocationTableRef'].getTableData();
      }
      if (this.baseInfo.type === 0) {
        params.commonProjectList = this.$refs['commonProjectRef'].getTableData();
      } else {
        params.travelProjectList = this.$refs['travelProjectRef'].getTableData();
      }
      params.approvalIds = this.$refs['associatedApprovalRef'].getTableData();
      return params;
    },
    // 回填表单数据
    setFormData(data) {
      data.proposerId && (this.$refs['baseInfoRef'].defaultProposer = [{ id: data.proposerId, userName: data.proposer }]);
      this.totalReimbursementAmount = data.totalReimbursementAmount;
      this.totalAllocationAmount = data.totalAllocationAmount;
      this.$refs['accountTableRef'].setTableData(data.accountInfo);
      this.$refs['associatedApprovalRef'].setTableData(data.approvalList);
      if (this.baseInfo.isAllocation === 1) {
        this.$refs['allocationTableRef'].setTableData(data.allocationList);
      }
      if (this.baseInfo.type === 0) {
        this.$refs['commonProjectRef'].setTableData(data.commonProjectList);
      } else {
        this.$refs['travelProjectRef'].setTableData(data.travelProjectList);
      }
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const params = this.getFormData();
      // params.type = 17;
      formSubmitReimbursement(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            const proposer = {
              id: this.baseInfo.proposerId,
              userName: this.baseInfo.proposer,
              avatar: this.baseInfo.avatar
            };
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, proposer);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(_ => {
        this.loading = false;
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      return !isContained(nowProcessIds, oldProcessIds);
    },
    submit(submitType = SUBMIT_TYPE.SUBMIT, senders = []) { // 1草稿 2保存提交 3重新提交
      this.modifySenders = senders;// 存到mixins
      const params = this.getFormData();
      params.submitType = submitType;
      params.isEditAudit = !!(this.remodifyId && this.isRefresh); // 修改时，流程被编辑或者更新
      params.auditInfo = this.auditInfo;
      if (this.createNew) {
        delete params.id;
      }
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      const msg = submitType === SUBMIT_TYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      this.$confirm(msg, '', {
        confirmButtonText: '确定', type: 'warning', showClose: false,
        center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
      }).then(() => {
        if (this.reapplyId || !this.isEdit) {
          this.add(params);
        } else {
          this.handleModifyData(params);
          this.edit(params);
        }
      });
    },
    add(params) {
      if (this.reapplyId && !this.createNew) params.submitType = SUBMIT_TYPE.RESUBMIT;
      storeReimbursement(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMIT_TYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'reimbursementDetail',
              query: {
                reimbursementId: res.data.id,
                processId: res.data.processId
              }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        this.loading = false;
      });
    },
    edit(params) {
      params.id = this.id;
      editReimbursement(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMIT_TYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.processId) {
            this.$router.push({
              name: 'reimbursementDetail',
              query: { reimbursementId: params.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'reimbursementDetail', params: {}, query: { reimbursementId: this.id, processId: this.remodifyId }});
        }
        this.loading = false;
      });
    },
    toBack() {
      this.$router.push({
        name: 'reimbursement'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.reimbursement-create-container {
  margin: 16px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
}
::v-deep .pagination-flex {
  justify-content: center;
}
.page-container {
  padding: 24px 24px 0;
  &.pb55 {
    padding-bottom: 55px;
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
</style>
